package org.apache.axis2.transport.p2p;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.description.TransportOutDescription;
import rice.environment.Environment;
import rice.pastry.NodeIdFactory;
import rice.pastry.PastryNode;
import rice.pastry.PastryNodeFactory;
import rice.pastry.socket.SocketPastryNodeFactory;
import rice.pastry.standard.RandomNodeIdFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * Created by IntelliJ IDEA.
 * User: shelan
 * Date: May 15, 2010
 * Time: 12:50:25 PM
 * To change this template use File | Settings | File Templates.
 */
public class P2pManager {

    public void start() {

        //put all the logic that you need to start this as the pastry ring
        // you need to get the details from the axis2.xml about the pastry boot node details.

    }


    public void initSender(ConfigurationContext cfgContext, TransportOutDescription outDescription) {


    }


    public void initReceiver(ConfigurationContext cfgContext, TransportInDescription inDescription) {

    }


    /**
     * 
     * @param outDescription
     * @throws IOException
     */
    public void initPastryRing(TransportOutDescription outDescription) throws IOException {

        // Loads pastry settings
        Environment env = new Environment();

        // disable the UPnP setting (in case you are testing this on a NATted LAN)
        env.getParameters().setString("nat_search_policy", "never");

        Parameter bootIp = outDescription.getParameter(P2pConstants.BOOT_IP);

        Parameter bootPort = outDescription.getParameter(P2pConstants.BOOT_PORT);

        Parameter bindPort = outDescription.getParameter(P2pConstants.BIND_PORT);


        // build the bootaddress from the parameters
        InetAddress bootAddress = InetAddress.getByName(bootIp.getName());

        int bootport = Integer.parseInt(bootPort.getName());

        InetSocketAddress bootaddress = new InetSocketAddress(bootAddress, bootport);

        int bindport = Integer.getInteger(bindPort.getName());


        // Generate the NodeIds Randomly
        NodeIdFactory nidFactory = new RandomNodeIdFactory(env);

        // construct the PastryNodeFactory, this is how we use rice.pastry.socket
        PastryNodeFactory factory = new SocketPastryNodeFactory(nidFactory, bindport, env);

        // construct a node
        PastryNode node = factory.newNode();

    }


}


